package midone.exchangeskill.net.dagger;


import java.util.concurrent.TimeUnit;


import dagger.Module;
import dagger.Provides;
import midone.exchangeskill.base.view.Application;
import midone.exchangeskill.net.api.ApiManager;
import midone.exchangeskill.net.api.ApiService;
import midone.exchangeskill.net.api.LogInterceptor;
import midone.exchangeskill.net.api.NetConstants;
import midone.exchangeskill.utils.NetWorkUtil;
import midone.exchangeskill.net.scope.ApiScope;
import midone.exchangeskill.utils.SharedPreferencesUtil;
import midone.exchangeskill.utils.ViewUtils;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by NekoNeko on 2016/11/7.
 */
@Module
@ApiScope
public class ApiModule {
    @Provides
    public Cache provideCache(Application application) {
        return new Cache(application.getCacheDir(), 10240 * 1024);
    }

    @Provides
    public LogInterceptor provideLogInterceptor(SharedPreferencesUtil sharedPreferencesUtil, ViewUtils viewUtils, NetWorkUtil netWorkUtil) {
        return new LogInterceptor(sharedPreferencesUtil, viewUtils, netWorkUtil);
    }

    @Provides
    public OkHttpClient provideOkHttp(LogInterceptor logInterceptor, Cache cache) {
        okhttp3.OkHttpClient.Builder builder = new okhttp3.OkHttpClient.Builder().addInterceptor(logInterceptor).cache(cache);
        OkHttpClient okHttpClient = builder.connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS).build();
        return okHttpClient;
    }

    @Provides
    public Retrofit provideRetrofit(OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .baseUrl(NetConstants.BASE_URL).client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 使用RxJava作为回调适配器
                .build();
    }

    @Provides
    public ApiService provideApiService(Retrofit retrofit) {
        return retrofit.create(ApiService.class);
    }

    @Provides
    public ApiManager provideApiManager(ApiService apiService) {
        return new ApiManager(apiService);
    }
}
